import type { ChatMessage } from "@/types/chat";

class OpenAI {
  private apiKey: string;
  private baseURL: string;

  constructor({ apiKey, baseURL }: { apiKey: string; baseURL: string }) {
    this.apiKey = apiKey;
    this.baseURL = baseURL;
  }

  chat = {
    completions: {
      create: async ({
        model,
        messages,
        temperature,
        onProgress,
      }: {
        model: string;
        messages: Array<{ role: string; content: string }>;
        temperature: number;
        onProgress?: (text: string) => void;
      }) => {
        try {
          return new Promise((resolve, reject) => {
            const requestTask = uni.request({
              url: `${this.baseURL}/chat/completions`,

              method: "POST",
              tags: ["upload_files"],
              header: {
                "Content-Type": "application/json",
                Authorization: `Bearer ${this.apiKey}`,
                Accept: "text/event-stream",
              },
              data: {
                model,
                messages,
                temperature,
                stream: true,
              },
              enableChunked: true,
              success: (res) => {
                if (res.statusCode === 200) {
                  resolve(res);
                } else {
                  reject(new Error(`HTTP Error: ${res.statusCode}`));
                }
              },
              fail: (err) => {
                reject(err);
              },
            });

            (requestTask as any).onChunkReceived((response: any) => {
              try {
                const chunk = new TextDecoder().decode(response.data);
                const lines = chunk
                  .split("\n")
                  .filter((line) => line.trim() !== "");

                for (const line of lines) {
                  if (line.startsWith("data: ")) {
                    const data = line.slice(6);
                    if (data === "[DONE]") continue;

                    try {
                      const parsed = JSON.parse(data);
                      const content = parsed.choices[0]?.delta?.content;
                      if (content) {
                        onProgress?.(content);
                      }
                    } catch (e) {
                      console.error("JSON parse error:", e);
                    }
                  }
                }
              } catch (error) {
                console.error("数据处理错误:", error);
              }
            });
          });
        } catch (error: any) {
          console.error("API Error:", error);
          throw error;
        }
      },
    },
  };
}

// 创建客户端实例
const client = new OpenAI({
  apiKey: "sk-P19VswMFE535Lbdgq4qJvUK8bQOIvVdhgEzl3HgXLVnbmBCM",
  baseURL: "https://api.moonshot.cn/v1",
});
// 克劳德专属api
// sk-tAXJLOprqHuPShNp6fJ6ZSFtxqegDDyd26Cx0iai0FTidgUP
// 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

export async function chatWithKimi(
  // input: ChatMessage[],
  input: string,
  onProgress?: (text: string) => void,
  maxRetries = 1
): Promise<string> {
  let retries = 0;

  while (retries < maxRetries) {
    try {
      let fullResponse = "";

      // 构建消息数组
      // const messages = [
      //   {
      //     role: "system",
      //     content: "你是宠物问答百科，请用中文回答用户的问题",
      //   },
      //   // ...input.map((item) => ({
      //   //   role: "user",
      //   //   content: item.content,
      //   // })),
      //   {
      //     role: "user",
      //     content: "你好",
      //   },
      // ];

      await client.chat.completions.create({
        model: "moonshot-v1-8k",
        messages: [
          {
            role: "system",
            content: "你是宠物问答百科，请用中文回答用户的问题",
          },
          {
            role: "user",
            content: input,
          },
        ],
        temperature: 0.3,
        onProgress: (text: string) => {
          fullResponse += text;
          onProgress?.(text);
        },
      });

      if (!fullResponse.trim()) {
        throw new Error("空响应");
      }

      return fullResponse;
    } catch (error: any) {
      retries++;
      console.error(`尝试 ${retries}/${maxRetries} 失败:`, error);

      if (retries === maxRetries) {
        onProgress?.("AI开了个小差，请稍后再试～");
        return "AI开了个小差，请稍后再试～";
      }

      // 等待后重试
      await new Promise((resolve) => setTimeout(resolve, 1000));
    }
  }

  onProgress?.("AI开了个小差，请稍后再试～");
  return "AI开了个小差，请稍后再试～";
}
